# Contributor: Mehdi Chinoune <mehdi.chinoune@hotmail.com>

_realname=mlir
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
_version=16.0.5
_rc=""
_tag=llvmorg-${_version}${_rc}
pkgver=${_version}${_rc/-/}
pkgrel=1
pkgdesc="Multi-Level IR Compiler Framework for LLVM (mingw-w64)"
url="https://mlir.llvm.org/"
arch=(any)
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
license=("custom:Apache 2.0 with LLVM Exception")
depends=("${MINGW_PACKAGE_PREFIX}-llvm")
makedepends=("${MINGW_PACKAGE_PREFIX}-clang"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
_pkgfn=${_realname}-${pkgver}.src
_url=https://github.com/llvm/llvm-project/releases/download/${_tag}
source=("${_url}/${_pkgfn}.tar.xz"{,.sig}
        "${_url}/cmake-${pkgver}.src.tar.xz"{,.sig}
        0001-do-not-link-to-llvm-dylib.patch)
sha256sums=('cc95a7afef6765fd9f823d3fd40191d67f361a06ed4cfad64ba819f2dff4c2a9'
            'SKIP'
            '9400d49acd53a4b8f310de60554a891436db5a19f6f227f99f0de13e4afaaaff'
            'SKIP'
            '5012547c4b7bde0d372f4d45bfc8ad93a9baee62e04e161460aa2a4ec2cc8c32')
validpgpkeys=('B6C8F98282B944E3B0D5C2530FC3042E345AD05D'  # Hans Wennborg, Google.
              '474E22316ABF4785A88C6E8EA2C794A986419D8A'  # Tom Stellard
              'D574BD5D1D0E98895E3BF90044F2485E45D59042') # Tobias Hieta
noextract=(llvm-project-${pkgver}.src.tar.xz)

prepare() {
  mv cmake-$pkgver.src cmake

  cd "${srcdir}"/${_pkgfn}
  patch -p1 -i "${srcdir}"/0001-do-not-link-to-llvm-dylib.patch
}

build() {
  mkdir -p build-${MSYSTEM} && cd build-${MSYSTEM}

  if check_option "debug" "y"; then
    _build_type="Debug"
  else
    _build_type="Release"
  fi

  CC=${MINGW_PREFIX}/bin/clang \
  CXX=${MINGW_PREFIX}/bin/clang++ \
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
    -GNinja \
    -DCMAKE_BUILD_TYPE=${_build_type} \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_SYSTEM_IGNORE_PATH=/usr/lib \
    -DLLVM_HOST_TRIPLE="${CARCH}-w64-windows-gnu" \
    -DPython3_EXECUTABLE=${MINGW_PREFIX}/bin/python.exe \
    -DLLVM_LINK_LLVM_DYLIB=ON \
    -DLLVM_BUILD_LLVM_DYLIB=ON \
    -DMLIR_LINK_MLIR_DYLIB=ON \
    -DLLVM_BUILD_TOOLS=ON \
    -DLLVM_BUILD_UTILS=ON \
    -DLLVM_ENABLE_PIC=ON \
    -DMLIR_INCLUDE_TESTS=OFF \
    -DCMAKE_C_VISIBILITY_PRESET=hidden \
    -DCMAKE_CXX_VISIBILITY_PRESET=hidden \
    -Wno-dev \
    ../$_pkgfn

  ${MINGW_PREFIX}/bin/cmake --build .
}

package() {
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install build-${MSYSTEM}

  install -d "$pkgdir${MINGW_PREFIX}"/share/licenses/${_realname}
  install -Dm644 ${srcdir}/${_pkgfn}/LICENSE* -t "$pkgdir${MINGW_PREFIX}"/share/licenses/${_realname}
}
